import { View, Button } from "@tarojs/components"
import React, { useEffect, useLayoutEffect, useState } from "react"

const EffectPage:React.FC = () => {
    const [num1, setNum1] = useState(0)
    const [num2, setNum2] = useState(0)

    // useEffect 中的回调函数在浏览器重新绘制屏幕之后触发
    useEffect(() => {
        if (num1 === 0) {
            setNum1(10 + Math.random() * 200)
          }
    }, [ num1 ])

    // useLayoutEffect 中的回调函数在浏览器重新绘制屏幕之前触发，可以避免闪烁
    useLayoutEffect(() => {
        if (num2 === 0) {
            setNum2(10 + Math.random() * 200)
          }
    }, [ num2 ])

    return <View className="page">
        <View className="row">{num1}</View>
        <Button size="mini" onClick={() => setNum1(0)}>useEffect重置</Button>
        <View className="row">{num2}</View>
        <Button size="mini" onClick={() => setNum2(0)}>useLayoutEffect重置</Button>
    </View>
}

export default EffectPage
